package admin.controllers;

import helpers.IdUniqueHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.IdCountData;
import admin.data.StaffData;
import admin.forms.StaffForm;

import models.StaffModel;

public class AddStaffServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		TreeMap check = new TreeMap();
		StaffModel user = new StaffModel();
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("user", user);

		try {
			request.getRequestDispatcher("/admin/pages/form_staff.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		StaffData uData = new StaffData();
		StaffModel user = new StaffModel();
		request.setAttribute("action", "add");
		
		//Check value valid form
		StaffForm staffForm = new StaffForm();
		TreeMap forms = (TreeMap) staffForm.checkValid(request, user); 
		user = (StaffModel) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		
		if(check.size() == 0)
	    {
			user.setCode(IdCountData.getIdByType("4"));
			user.setPassword(StringHelper.md5(user.getPassword()));
			uData.insert(user);
			request.setAttribute("success", "Thêm nhân viên " + user.getUsername() + " thành công");
			user = new StaffModel();
	    }
		
		request.setAttribute("form", "add");
		request.setAttribute("check", check);
		request.setAttribute("user", user);
		try {
			request.getRequestDispatcher("/admin/pages/form_staff.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
